package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDao userDao;


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (queryString != null) {
            queryString = "%" + queryString + "%";
        }
        PageHelper.startPage(currentPage , pageSize);
        Page<Role> page = roleDao.findPage(queryString);

        return new PageResult(page.getTotal() , page.getResult());
    }

    @Override
    public Role findById(int id) {
        return roleDao.findById(id);
    }

    @Override
    public void add(Role role , Integer[] permissionIds) {
        roleDao.add(role);
        Integer roleId = role.getId();//检查组id
        //设置角色和权限多对多关系
        this.setRoleAndPermission(roleId , permissionIds);
    }

    @Override
    public void edit(Role role , Integer[] permissionIds) {
        roleDao.edit(role);
        Integer roleId = role.getId();
        roleDao.deleteAssociation4Permission(roleId);
        //设置角色和权限多对多关系
        this.setRoleAndPermission(roleId , permissionIds);
    }

    @Override
    public void deleteById(Integer roleId) {
        long count = userDao.findByRoleId(roleId);
        if (count > 0 ) {
            // 有关联的用户，不能删除
            throw new RuntimeException("该角色已有关联的用户，无法删除");
        } else {
            // 没有关联的用户或菜单，可以删除
            // 删除角色和权限的关联
            roleDao.deleteAssociation4Permission(roleId);
            roleDao.deleteAssociation4Menu(roleId);
            roleDao.deleteById(roleId);
        }
    }

    private void setRoleAndPermission(Integer roleId , Integer[] permissionIds) {
        //设置多对多关系
        if (permissionIds != null && permissionIds.length > 0) {
            for (Integer permissionId : permissionIds) {//检查项id
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId" , roleId);
                map.put("permissionId" , permissionId);
                roleDao.setCheckGroupAndCheckItem(map);
            }
        }
    }


}
